package ch.ti.bfh.app.loodel.internal;


import ch.ti.bfh.app.loodel.service.LoodelUserDetails;
import ch.ti.bfh.app.loodel.service.UserContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component(value = "userContext")
public class SpringSecurityUserContext implements UserContext {

    @Override
    public LoodelUserDetails getCurrentUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext == null || securityContext.getAuthentication() == null) {
            return null;
        }
        Authentication authentication = securityContext.getAuthentication();
        return extractFromAuthentication(authentication);
    }

    public static LoodelUserDetails extractFromAuthentication(Authentication authentication) {
        if (authentication.getPrincipal() instanceof LoodelUserDetails) {
            return (LoodelUserDetails) authentication.getPrincipal();
        }
        return null;
    }

}
